package com.sgb.kjwl.view.ui.activity.self.websiteManage;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityWebsiteDetail3Binding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.self.WebsiteDetailEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.GlideEngine;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.viewmodel.self.website.WebsiteDetailModel3;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class WebsiteDetailActivity3 extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    private ActivityWebsiteDetail3Binding binding;

    private List<String> imgList;
    // 一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    private List<List<AddressEntity<List<AddressEntity>>>> opt2;
    // 三级联动数据
    private List<List<List<AddressEntity>>> opt3;
    //城市列表
    private List<AddressEntity<List<AddressEntity>>> cityList;
    //区域列表
    private List<List<AddressEntity>> areaList;
    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;

    private boolean isLoaded = false;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private File file;
    private String companyId = "";

    @Inject
    WebsiteDetailModel3 detailModel;

    public static void start(Context context,String id){
        Intent intent = new Intent(context, WebsiteDetailActivity3.class);
        intent.putExtra("companyId",id);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder()
                .appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_website_detail3);
        binding.include.ivBack.setOnClickListener(this);
        binding.include.titleView.setText("企业信息");
        binding.setViewModel(detailModel);

        binding.companyAddress.setOnWholeItemClickListener(this);
        binding.companyVideo.setOnWholeItemClickListener(this);
        binding.companyIntroduce.setOnWholeItemClickListener(this);
        binding.companyBuss.setOnWholeItemClickListener(this);
        binding.companyImgLayout.setOnClickListener(this);
        binding.tvSave.setOnClickListener(this);

        binding.companyPhone.setInputType(InputType.TYPE_CLASS_NUMBER);
        binding.companyTel.setInputType(InputType.TYPE_CLASS_NUMBER);
        binding.companyEmail.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);

    }

    @Override
    protected void init() {
        imgList = new ArrayList<>();
        opt2 = new ArrayList<>();
        opt3 = new ArrayList<>();

        companyId = getIntent().getStringExtra("companyId");
        detailModel.getDetail(companyId);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.company_img_layout:
                PictureSelector.create(WebsiteDetailActivity3.this)
                        .openGallery(PictureMimeType.ofImage())
                        .loadImageEngine(GlideEngine.createGlideEngine())
                        .theme(R.style.picture_default_style)
                        .selectionMode(PictureConfig.SINGLE)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            case R.id.tv_save:
                checkData();
                break;
        }
    }

    public void showDetail(WebsiteDetailEntity entity){
        detailModel.detailEntity.set(entity);

        Glide.with(getActivity()).load(entity.getCompanyLogo())
                .apply(RequestOptions.bitmapTransform(new CircleCrop()).placeholder(R.drawable.icon_no_logo))
                .into(binding.companyLogo);
    }

    public void checkData(){
        if(TextUtils.isEmpty(detailModel.detailEntity.get().getCompanyLogo()) && (null==imgList || imgList.size()==0 || null==file)){
            MToast.showToast(WebsiteDetailActivity3.this, "请上传企业LOGO");
            return;
        }/*else if(TextUtils.isEmpty(binding.companyBuss.getContent())){
            MToast.showToast(WebsiteDetailActivity3.this, "请填写主营业务");
            return;
        }else if (TextUtils.isEmpty(binding.companyAddress.getContent())) {
            MToast.showToast(WebsiteDetailActivity3.this, "请选择企业所在地");
            return;
        }else if (TextUtils.isEmpty(binding.companyDetailLocation.getText().toString())) {
            MToast.showToast(WebsiteDetailActivity3.this, "请填写企业详情地址");
            return;
        }else if (TextUtils.isEmpty(binding.companyPhone.getContent())) {
            MToast.showToast(WebsiteDetailActivity3.this, "请输入联系电话");
            return;
        }*/ else if (!TextUtils.isEmpty(binding.companyPhone.getContent()) && !CheckUtils.isMobileNum(binding.companyPhone.getContent())) {
            Toast.makeText(this, "请填写正确的联系电话", Toast.LENGTH_SHORT).show();
            return;
        } else if (!TextUtils.isEmpty(binding.companyTel.getContent()) && !CheckUtils.IsTelephone(binding.companyTel.getContent())) {
            Toast.makeText(this, "请填写正确的座机号", Toast.LENGTH_SHORT).show();
            return;
        } /*else if (TextUtils.isEmpty(binding.companyUser.getContent())) {
            MToast.showToast(WebsiteDetailActivity3.this, "请输入联系人");
            return;
        }*/else if (!TextUtils.isEmpty(binding.companyUser.getContent()) && !CheckUtils.isEmail(binding.companyEmail.getContent())) {
            MToast.showToast(WebsiteDetailActivity3.this, "请填写正确的邮箱");
            return;
        }

        if(null==file && !TextUtils.isEmpty(detailModel.detailEntity.get().getCompanyLogo())){
            detailModel.saveData();
        }else{
            detailModel.uploadMutiFileModel(file,1);
        }
    }

    public void uploadImgSuccess(String urls){
        detailModel.detailEntity.get().setCompanyLogo(urls);
        detailModel.saveData();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片结果回调
                // 图片、视频、音频选择结果回调
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                file = new File(selectList.get(0).getRealPath());
                MLog.d("图片路径：", selectList.get(0).getRealPath());
                if (file.exists()) {
                    MLog.d("图片", "存在");
                }
                imgList.clear();
                imgList.add(selectList.get(0).getRealPath());
                Glide.with(WebsiteDetailActivity3.this).load(selectList.get(0).getRealPath()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(binding.companyLogo);
            }else if(requestCode == 300){
                String videoId = data.getStringExtra("videoId");
                if(!TextUtils.isEmpty(videoId)){
                    detailModel.detailEntity.get().setVideoId(videoId);
                }
            }
        }
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()){
            case R.id.company_address:
                if (addressEntityList != null) {
                    showCityPop();
                } else {
                    detailModel.getAddressModel();
                }
                break;
            case R.id.company_buss:

                break;
            case R.id.company_video:
                //上传视频
                Intent intent = new Intent(WebsiteDetailActivity3.this,WebsiteVideoActivity3.class);
                if(!TextUtils.isEmpty(detailModel.detailEntity.get().getPlayUrl())){
                    intent.putExtra("playerUrl",detailModel.detailEntity.get().getPlayUrl());
                    intent.putExtra("playerTime",detailModel.detailEntity.get().getPlayDuration());
                }
                startActivityForResult(intent,300);
//                WebsiteVideoActivity3.start(WebsiteDetailActivity3.this);
                break;
            case R.id.company_introduce:
                //企业简介
                WebsiteIntroduceActivity3.start(WebsiteDetailActivity3.this,detailModel.detailEntity.get().getIntroduce());
                break;
        }
    }

    //地址数据
    public void showAddressPop(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        this.addressEntityList = datas;
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            // 子线程中解析省市区数据
                            initJsonData();
                        }
                    }).start();
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    break;
            }
        }
    };

    private void initJsonData() {
        for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> entity : addressEntityList) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            opt2.add(entity.getChildren());
            for (int i = 0; i < entity.getChildren().size(); i++) {
                cityList.add(entity.getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (entity.getChildren().get(i).getChildren() == null
                        || entity.getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(entity.getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    private void showCityPop() {

        /*if (!TextUtils.isEmpty(id)) {
            for (int i = 0; i < addressEntityList.size(); i++) {
                if (addressEntityList.get(i).getId().equals(viewModel.addGoodsEntity.get().getProvinceNo())) {
                    cityPosition1 = i;
                    break;
                }
            }

            for (int i = 0; i < addressEntityList.get(cityPosition1).getChildren().size(); i++) {
                if (addressEntityList.get(cityPosition1).getChildren().get(i).getId().equals(viewModel.addGoodsEntity.get().getCityNo())) {
                    cityPosition2 = i;
                    break;
                }
            }

            for (int i = 0; i < addressEntityList.get(cityPosition1).getChildren().get(cityPosition2).getChildren().size(); i++) {
                if (addressEntityList.get(cityPosition1).getChildren().get(cityPosition2).getChildren().get(i).getId().equals(viewModel.addGoodsEntity.get().getDistrictNo())) {
                    cityPosition3 = i;
                    break;
                }
            }
        }*/

        //条件选择器
        CityPickView cityOption = new CityPickBuilder(WebsiteDetailActivity3.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String areaName;
                if (opt3.get(options1).get(options2).get(options3) == null) {
                    areaName = "";
                } else {
                    areaName = opt3.get(options1).get(options2).get(options3).getName();
                    cityPosition3 = options3;
                    detailModel.detailEntity.get().setDistrictNo(opt3.get(options1).get(options2).get(options3).getNo());
                    detailModel.detailEntity.get().setDistrictName(opt3.get(options1).get(options2).get(options3).getName());

                }
                String content = addressEntityList.get(options1).getName()
                        + opt2.get(options1).get(options2).getName()
                        + areaName;
                binding.companyAddress.setContent(content);
                cityPosition1 = options1;
                cityPosition2 = options2;

                detailModel.detailEntity.get().setCityNo(opt2.get(options1).get(options2).getNo());
                detailModel.detailEntity.get().setCityName(opt2.get(options1).get(options2).getName());
                detailModel.detailEntity.get().setProvinceNo(addressEntityList.get(options1).getNo());
                detailModel.detailEntity.get().setProvinceName(addressEntityList.get(options1).getName());
            }
        }).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

}
